package xzr4;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class ItemTest {
    private JFrame jf;
    private JComboBox jcb1,jcb2;
    private JLabel label1,label2;
    private String[] shengfen;
    private String[][] city;

    public ItemTest(String[] shengfen, String[][] city) {
        this.shengfen = shengfen;
        this.city = city;
        jf = new JFrame("下拉测试！");
        jcb1 = new JComboBox(shengfen);
        jcb2 = new JComboBox(city[0]);
        label1 = new JLabel("省份：");
        label2 = new JLabel("城市：");

        jf.setLayout(new FlowLayout());
        jf.add(label1);
        jf.add(jcb1);
        jf.add(label2);
        jf.add(jcb2);
        addEventHandler();
    }
    public void addEventHandler(){
        jcb1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                int index = jcb1.getSelectedIndex();
                jcb2.removeAllItems();
                for (int i = 0; i < city[index].length; i++) {
                    jcb2.addItem(city[index][i]);
                }
            }
        });
    }
    public void showMe(){
        jf.setSize(400,300);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        String[] pri = { "==请选择==", "河北", "山东", "江苏", "浙江", "陕西" };
        String[][] city = { { "==请选择==" }, { "石家庄", "保定", "邯郸", "唐山", "秦皇岛" },
                { "济南", "青岛", "烟台", "威海", "潍坊" },
                { "南京", "苏州", "无锡", "常州", "连云港" },
                { "杭州", "温州", "宁波", "金华", "台州" },
                { "西安", "咸阳", "汉中", "延安", "宝鸡" } };
        new ItemTest(pri, city).showMe();
    }
}
